import logging
import re
import requests
from urllib.parse import urljoin


def get_favicon_url(url):
    # 确保 URL 以 http(s) 开头
    if not url.startswith(('http://', 'https://')):
        url = 'https://' + url

    try:
        response = requests.get(url, timeout=2)
        response.raise_for_status()  # 检查请求是否成功
        text = response.text

        # 使用正则表达式匹配 favicon 链接
        regex = r'<link.*?rel=["\']?(icon|shortcut icon)["\']?[^>]*href=["\']([^"\']+)["\']'
        match = re.search(regex, text, re.IGNORECASE)

        if match and match.group(2):
            return urljoin(url, match.group(2))  # 返回绝对路径
        else:
            # 如果没有找到 favicon，则返回默认路径
            return urljoin(url, '/favicon.ico')
    except requests.Timeout:
        logging.info(f"请求超时: {url}")
        return None
    except requests.ConnectionError:
        logging.info(f"连接错误: {url}")
        return None
    except requests.HTTPError as http_err:
        logging.info(f"HTTP错误: {http_err}，URL: {url}")
        return None
    except Exception as error:
        logging.info(f"获取图标失败: {error}，URL: {url}")
        return None
